var roleManager_page={};

roleManager_page.action = {
    initBody:function () {
        roleManager_page.interface.initTablePage();
        roleManager_page.action.bindEvent();
    },
    bindEvent:function () {
        $("#addBtn").click(function () {
            roleManager_page.interface.initFormPage();
            // roleManager_page.action.bindEvent();
            return false;
        });
        $("#saveBtn").click(function () {
            roleManager_page.action.saveBtnClick();
            return false;
        });
        $("#saveBtnMenu").click(function () {
            roleManager_page.action.saveMenuForm();
        });
        $("#cancelBtn").click(function () {
            roleManager_page.action.initBody();
            return false;
        });
    },

    bindEventClose:function () {
        $(".close").click(function(){
            this.remove();
        })
    },
    saveBtnClick:function () {
        var groupId = $("#groupId").val()
        if ($.isEmpty(groupId)) {
            layer.alert('所属组织不能为空。', {
                icon: 0,
                skin: 'layer-ext-moon'
            });
            return false;
        }
        var orderId = $("#orderId").val();
        if ($.isEmpty(orderId)) {
            layer.alert('排序号不能为空。', {
                icon: 0,
                skin: 'layer-ext-moon'
            });
            return false;
        } else if (!$.isNumber(orderId)) {
            layer.alert('排序号必须为数字。', {
                icon: 0,
                skin: 'layer-ext-moon'
            });
            return false;
        }

        var param = {
            id: $("#orderId").val(),
            roleName: $("#roleName").val(),
            comment: $("#comment").val(),
            groupId: groupId,
            orderId: orderId,
            groupName: $("#groupName").val()
        };
        var onSuccess = function (resultData) {
            if (resultData.success) {
                roleManager_page.action.initBody();
                layer.msg("保存成功！", {icon: 1});
            } else {
                layer.msg("保存失败！", {icon: 2});
            }
        };
        AppComm.ajax.execute({
            'url':AppComm.url.getBaseURL()+'/roleManager/ajax/saveRole',
            'data':param,
            'success':onSuccess
        });
    },
    //保存配置菜单权限
    saveMenuForm:function () {
        var dataId = $("#dataId").val();
        var nodesArray = roleManager_page.data.ztreeChecked.getCheckedNodes();
        var menuArray = new Array();
        for(var i=0;i<nodesArray.length;i++){
            menuArray.push(nodesArray[i].id);
        }
        var menuIds = JSON.stringify(menuArray);
        var params={
            id:dataId,
            menuIds:menuIds
        };
        var onSuccess = function (resultData) {
            if (resultData.success) {
                layer.msg("保存成功！", {icon: 1});
            } else {
                layer.msg("保存失败！", {icon: 2});
            }
        };
        AppComm.ajax.execute({
            'url':AppComm.url.getBaseURL()+'/roleManager/ajax/saveMenuPer',
            'data':params,
            'success':onSuccess
        });
    },

    deleteRole:function (roleId) {
        var params = {
            id:roleId
        };
        var onSuccess = function (resultData) {
            if (resultData.success) {
                layer.msg("删除成功！", {icon: 1});
                roleManager_page.data.tableIns.reload();
            }
        };
        AppComm.ajax.execute({
            'url':AppComm.url.getBaseURL()+'/roleManager/ajax/deleteRole',
            'data':params,
            'success':onSuccess
        });
    },
    // 保存操作授权
    saveOperations:function (roleId, operationIds) {
        var operationD = new Array();
        for (var i=0; i<operationIds.length; i++) {
            operationD.push(operationIds[i].value);
        }
        var ids = operationD.join(",");
        var params= {
            id:roleId,
            ids:ids
        };
        var onSuccess1 = function (resultData) {
            if (resultData.success) {
                layer.msg("配置成功！", {icon: 1});
            }
        };
        AppComm.ajax.execute({
            'url':AppComm.url.getBaseURL()+'/roleManager/ajax/saveOpationPer',
            'data':params,
            'success':onSuccess1
        });
    }
};
roleManager_page.interface = {
    // 加载表格页
    initTablePage: function () {
        var html = template("roleManagerList_template");
        $(".roleManager_box").html(html);

        layui.use(['table', 'form'], function () {
            var table = layui.table;

            //执行表格渲染
            var tableIns = table.render({
                height: 625,
                url: AppComm.url.getBaseURL() + '/roleManager/ajax/getRoleManagerList',
                elem: "#tb_list",
                page: true,
                limit: 14,
                loading: true,
                id: 'id',
                cols: [[
                    // {
                    //     field: 'roleKey',
                    //     title: '角色关键字',
                    //     align:'left',
                    // },
                    {
                        field: 'roleName',
                        title: '角色名称',
                        width: 200,
                        align:'left',
                    },{
                        field:'orderId',
                        title:'排序号',
                        edit: 'text',
                        align:'left',
                        width:100
                    },{
                        field:'groupName',
                        title:'所属组织',
                        align:'left',
                        width:200
                    },{
                        field: 'comment',
                        title: '说明',
                        align:'left',
                        width:300
                    }, {
                        title: '操作',
                        fixed: 'right',
                        width: 280,
                        align: 'center',
                        toolbar: '#toolbar'
                    }
                ]]
            });

            roleManager_page.data.tableIns = tableIns;

            table.on('tool(tb_list)', function (obj) {
                var rowData = obj.data;
                var layEvent = obj.event;
                if (layEvent === 'editBtn') {
                    roleManager_page.interface.initFormPage(rowData.id);
                }
                if (layEvent === 'menuBtn') {
                    roleManager_page.interface.initMenuPage(rowData.id);
                    roleManager_page.action.bindEvent();
                }
                if (layEvent === 'operateBtn') {
                    roleManager_page.interface.initOperatePage(rowData.id);
                }
                if (layEvent === 'deleteBtn') {
                    // if(rowData.roleKey=="admin"){
                    //     layer.msg("系统管理员角色不能删除！！",{icon: 2});
                    // }else{
                        layer.confirm('确定要进行删除吗？', {icon: 3, title: '提示'}, function (index) {
                            roleManager_page.action.deleteRole(rowData.id);
                            layer.close(index);
                        }, function (index) {
                            layer.close(index);
                        });
                    // }
                }
            });
            table.on('edit(tb_list)', function(obj){
                var param ={
                    id:obj.data.id,
                    orderId:obj.value,
                };
                var onSuccess = function (resultData) {
                    if (resultData.success) {
                        layer.msg("排序号已修改！", {icon: 1});
                        roleManager_page.action.initBody();
                    } else {
                        layer.msg("修改失败！", {icon: 2});
                    }
                };
                AppComm.ajax.execute({
                    'url': AppComm.url.getBaseURL() + '/roleManager/ajax/updateOrderId',
                    'data': param,
                    'success': onSuccess
                });
            });
            // 查询
            var form = layui.form;
            form.render(null, 'searchForm');
            form.on('submit(searchBtn)', function (data) {
                var postData = {
                    roleName: data.field.nameInput
                };
                tableIns.reload({
                    page: {curr:1},
                    where: postData
                });
                return false;
            });
        });

    },
    // 初始化表单页
    initFormPage: function (dataId) {
        if (dataId == undefined || '' == dataId.trim()) {
            // 添加
            var onSuccess = function (resultData) {
                if (resultData.success) {
                    var html = template("roleManagerForm_template", resultData.data);
                    $(".roleManager_box").html(html);
                    roleManager_page.action.bindEvent();
                    if (AppComm.permission.isAdministrator()) {
                        $("#groupNameInput").css("display","block");
                        $("#groupNameShow").css("display","none");
                    } else {
                        $("#groupNameInput").css("display","none");
                        $("#groupNameShow").css("display","block");
                    }
                    $("#groupName").click(function () {
                        roleManager_page.interface.initGroupPage();
                        return false;
                    });
                }
            };
            AppComm.ajax.execute({
                'url':AppComm.url.getBaseURL()+'/roleManager/ajax/getCurrGroupInfo',
                'data':null,
                'success':onSuccess
            });

            // layui.use('form', function(){
            //     var form = layui.form;
            //     form.verify({
                    // roleKey:function(value){
                    //     var flag = 0;
                    //     var params={
                    //         roleKey:value,
                    //     };
                    //     var onSuccess = function (resultData) {
                    //         if (resultData.success) {
                    //             if(resultData.data!=null){
                    //                 flag++;
                    //             }
                    //         }
                    //     };
                    //     AppComm.ajax.execute({
                    //         'url':AppComm.url.getBaseURL()+'/roleManager/ajax/getRoleListByKey',
                    //         'data':params,
                    //         'async':false,
                    //         'success':onSuccess
                    //     });
                    //     if(flag>0){
                    //        return "角色关键字已存在";
                    //     }
                    //
                    // },
                //     groupId:function (value) {
                //         if ($.isEmpty(value)) {
                //             return '所属组织不能为空。';
                //         }
                //     },
                //     orderId:function(value){
                //         if(!$.isNumber(value)){
                //             return '排序号必须为数字';
                //         }
                //         if($.isEmpty(value)){
                //             return '排序号不能为空';
                //         }
                //     }
                // });

                // form.on('submit(submitBtn)', function(data){
                //     data.field.id=dataId;
                //     var onSuccess = function (resultData) {
                //         if (resultData.success) {
                //             layer.msg("保存成功！");
                //             // roleManager_page.action.initBody();
                //         } else {
                //             layer.msg("保存失败！");
                //         }
                //     };
                //     AppComm.ajax.execute({
                //         'url':AppComm.url.getBaseURL()+'/roleManager/ajax/saveRole',
                //         'data':data.field,
                //         'success':onSuccess
                //     });
                // });
            // });
        } else {
            // 编辑
            layer.load();
            var params = {
                id: dataId
            };
            var onSuccess = function (resultData) {
                layer.closeAll('loading');
                var html = template("roleManagerForm_template", resultData.data);
                $(".roleManager_box").html(html);
                roleManager_page.action.bindEvent();

                if (AppComm.permission.isAdministrator()) {
                    $("#groupNameInput").css("display","block");
                    $("#groupNameShow").css("display","none");
                } else {
                    $("#groupNameInput").css("display","none");
                    $("#groupNameShow").css("display","block");
                }
                $("#groupName").click(function () {
                    roleManager_page.interface.initGroupPage();
                    return false;
                });

                $("#roleKey_div").hide();
                // layui.use('form', function(){
                //     var form = layui.form;
                //     form.verify({
                //         orderId:function(value){
                //             if(!$.isNumber(value)){
                //                 return '排序号必须为数字';
                //             }
                //             if($.isEmpty(value)){
                //                 return '排序号不能为空';
                //             }
                //         }
                //     });
                //
                //     form.on('submit(submitBtn)', function(data){
                //         data.field.id = dataId;
                //         var onSuccess = function (resultData) {
                //             if (resultData.success) {
                //                 layer.msg("保存成功！");
                //                 // roleManager_page.action.initBody();
                //             } else {
                //                 layer.msg("保存失败！");
                //             }
                //         };
                //         AppComm.ajax.execute({
                //             'url':AppComm.url.getBaseURL()+'/roleManager/ajax/saveRole',
                //             'data':data.field,
                //             'success':onSuccess
                //         });
                //     });
                // });
            };
            AppComm.ajax.execute({
                'url': AppComm.url.getBaseURL() + '/roleManager/ajax/getRoleById',
                'data': params,
                'success': onSuccess
            });
        }


    },
    //初始化菜单授权页
    initMenuPage: function (dataId) {
        var ztreeLoad = layer.load();
        var params = {
            id: dataId,
        };

        var html = template("roleManagerForm_ztree", {});
        var roleAuthLayer = layer.open({
            type: 1,
            area: ['420px', '440px'], //宽高
            btn: ['提交', '取消'], //可以无限个按钮
            yes: function(index, layero){
                layer.close(roleAuthLayer);
                roleManager_page.action.saveMenuForm();
            },
            btnAlign: 'c',
            content: html
        });

        $("#dataId").val(dataId);
        var ztree = new CommonZtree('treeDemo', '/roleManager/ajax/getMenuZtree', params);
        ztree.setZtreeCheck(true);
        ztree.ztreeInit();
        roleManager_page.data.ztreeChecked = ztree;
        layer.close(ztreeLoad);
    },
    //选择组织界面初始化
    initGroupPage: function () {
        var html = template("roleManagerList_group", {});
        var groupLayer = layer.open({
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: '720px', //宽高
            offset: '50px',
            content: html
        });
        layui.use(['table', 'form'], function () {
            var table = layui.table;
            //执行表格渲染
            var groupTable = table.render({
                elem: "#group_list",
                url: AppComm.url.getBaseURL()+'/groupManager/ajax/getGroupList',
                page: {
                    layout: ['count', 'prev', 'page', 'next', 'skip']
                },
                limit: 10,
                heigth:"600px",
                loading: true,
                id: 'group_list',
                cols: [[
                    {
                        field: 'groupName',
                        title: '组织名称',
                        width: 200,
                        align: 'left',
                        event: 'setSign',
                    },
                    {
                        field: 'parentName',
                        title: '上级组织',
                        width: 200,
                        align: 'left',
                        event: 'setSign',
                    },
                    {
                        field: 'comment',
                        title: '组织说明',
                        width: 200,
                        align: 'left',
                        event: 'setSign',
                    }
                ]]
            });

            table.on('tool(group_list)', function (obj) {
                var rowData = obj.data;
                roleManager_page.data.currGroupId = rowData.id;
                $("#groupName").val(rowData.groupName);
                $("#groupId").val(rowData.id);
                // var layEvent = obj.event;
                layer.close(groupLayer);

            });
            // 查询
            var form = layui.form;
            form.render(null, 'searchGroupForm');
            form.on('submit(searchGroup)', function (data) {
                var postData = {
                    groupName: data.field.groupNameInput
                };
                groupTable.reload({
                    page: {curr:1},
                    where: postData
                });
                return false;
            });
            return;
        });
    },
    //初始化操作授权页
    initOperatePage: function (dataId) {
        var html = template("roleManagerList_operation", {});

        var operateLayer = layer.open({
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: '480px', //宽高
            offset: '50px',
            content: html,
            btnAlign: 'c',
            btn: ['提交', '取消'], //可以无限个按钮
            yes: function(index, layero){
                layer.close(operateLayer);
                var getData = roleManager_page.data.transfer.getData("transferId");
                roleManager_page.action.saveOperations(dataId, getData);
            },
        });
        var onSuccess = function (resultData) {
            console.log(resultData.data);
            if (resultData.success) {
                layui.use(['transfer', 'layer', 'util'], function(){
                    var $ = layui.$
                        ,transfer = layui.transfer
                        ,layer = layui.layer
                        ,util = layui.util;
                    roleManager_page.data.transfer = transfer;
                    roleManager_page.data.transfer.render({
                        id:'transferId',
                        elem: '#transfer',
                        title: ['未授权操作', '已授权操作'],
                        showSearch: true,
                        data: resultData.data.allOperations,
                        value: resultData.data.haveOperations
                    })

                });
            }
        };
        var params = {
            id:dataId
        };
        AppComm.ajax.execute({
            'url':AppComm.url.getBaseURL()+'/operationManager/ajax/getOperationByRoleIdTransfer4Role',
            'data':params,
            'success':onSuccess
        });
    }

};

roleManager_page.data = {
    'tableIns':undefined,
    ztreeChecked:null,
    operationTable:null,
    tableData:[],
    'currGroupId':''
};


AppComm.initFrame(roleManager_page);